<template>
  <el-card>
    <el-table :data="category1List" style="width: 100%" :row-key="getRowKey" border lazy :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="id" label="分类ID" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="address" label="Address">
        <template #header>
          <el-input placeholder="按enter键添加一级分类"></el-input>
        </template>
        <el-button type="primary" :icon="Plus"></el-button>
        <el-button type="warning" :icon="Edit" size="small"></el-button>
        <el-button type="danger" :icon="Delete" size="small"></el-button>
      </el-table-column>
    </el-table>
  </el-card>
</template>
  
<script lang="ts">
export default {
  name: "Category",
};
</script>
<script lang="ts" setup>
import type { CategoryListModel, CategoryModel } from '@/api/product/model/CategoryStateModel';
import { onMounted, ref } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { reqGetCategory1ListData, reqGetCategory2ListData, reqGetCategory3ListData } from '@/api/product/category';
const category1List = ref<CategoryListModel>([])

//获取一级数据
onMounted(async () => {
  const result = await reqGetCategory1ListData()
  // console.log(result)
  category1List.value = result

  category1List.value.forEach(item => {
    item.hasChildren = true
    item.level = 1
  })
})

const load = async (
  row: CategoryModel,
  treeNode: unknown,
  resolve: (date: CategoryModel[]) => void
) => {
  if (row.level === 1) {
    let category2List = []
    const result = await reqGetCategory2ListData(row.id)
    category2List = result;
    category2List.forEach(item => {
      item.hasChildren = true
      item.level = 2
    })
    resolve(category2List);
  } else if (row.level === 2) {
    let category3List = []
    const result = await reqGetCategory3ListData(row.id)
    category3List = result;
    category3List.forEach(item => {
      item.hasChildren = false
      item.level = 3
    })
    resolve(category3List);
  }
}

//为了避免死递归  加一个唯一的key
const getRowKey = (row: CategoryModel) => {
  return `${row.id}-${row.level}`
} 
</script>
  
<style scoped></style>